﻿using Framework;

namespace Game
{
    public class SceneObjectBeHitActionable : IBTreeActionable<SceneObjectBTContext>
    {
        private SceneBattleObjectBTContext _context;
        
        public void OnStart(SceneObjectBTContext context)
        {
            _context = context as SceneBattleObjectBTContext;
            context.sceneObject.GetComponent<SceneObjectActionComponent>().SetTrigger(SceneObjectActions.BeHit);
            Scheduler.Instance.AddTimeListener(SceneConst.BeHitDuration, OnBeHitEnd);
        }

        public void OnEnd(SceneObjectBTContext context)
        {
            Scheduler.Instance.RemoveTimeListener(OnBeHitEnd);
        }

        public TaskStatus Update(SceneObjectBTContext context)
        {
            return TaskStatus.Running;
        }

        private void OnBeHitEnd(float deltaTime)
        {
            _context.attackEntity = null;
            if (_context.sceneObject.GetComponent<SceneObjectBattlePropertiesComponent>()
                .GetProperty(SceneObjectBattlePropertyKeys.Hp) <= 0)
            {
                _context.isDied = true;
            }
        }
    }
}